<template>
  <div class="app-container">
    <span style="font-size: medium;color: rgba(151,170,195) "> / 采购订单 / 订单生成</span>

    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="85px" style="margin-top: 20px">
      <el-form-item label="货品名称" prop="rawProductName">
        <el-input
            v-model="queryParams.rawProductName"
            placeholder="请输入货品名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="需求日期" prop="demandDate">
        <el-date-picker clearable
                        v-model="queryParams.demandDate"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择需求日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="购买状态" prop="purchaseStatus">
        <el-select v-model="queryParams.purchaseStatus">
          <el-option
              v-for="item in plan_purchase_status"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="sortedList" @selection-change="handleSelectionChange"
              style="margin-top: 10px;">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="采购计划编号" fixed align="center" prop="planNo" width="160px"/>
      <el-table-column label="货品名称" align="center" prop="rawProductName" width="140px"/>
      <el-table-column label="预期购买数量(吨)" align="center" prop="quantity" width="140px"/>
      <el-table-column label="已购数量(吨)" align="center" prop="purchaseQuantity" width="140px"/>
      <el-table-column label="购买状态" align="center" prop="purchaseStatus">
        <template #default="scope">
          <el-tag :type="getPlanPurchaseStatus(scope.row.purchaseStatus)" disable-transitions>
            {{ scope.row.purchaseStatus}}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="需求日期" align="center" prop="demandDate" width="160">
        <template #default="scope">
          <span>{{ parseTime(scope.row.demandDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预期交货时间" align="center" prop="expectedDeliveryTime" width="160">
        <template #default="scope">
          <span>{{ parseTime(scope.row.expectedDeliveryTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" fixed="right" header-align="center" align="left" prop="remarks" width="200"/>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改采购计划对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="ordergenerateRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="供应商编码" prop="supplierCode">
          <el-input v-model="form.supplierCode" placeholder="请输入供应商编码" />
        </el-form-item>
        <el-form-item label="货品名称" prop="rawProductName">
          <el-input v-model="form.rawProductName" placeholder="请输入货品名称" />
        </el-form-item>
        <el-form-item label="货品件数" prop="quantity">
          <el-input v-model="form.quantity" placeholder="请输入货品件数" />
        </el-form-item>
        <el-form-item label="预算" prop="budget">
          <el-input v-model="form.budget" placeholder="请输入预算" />
        </el-form-item>
        <el-form-item label="货币单位" prop="currencyUnit">
          <el-input v-model="form.currencyUnit" placeholder="请输入货币单位" />
        </el-form-item>
        <el-form-item label="预期交货时间" prop="expectedDeliveryTime">
          <el-date-picker clearable
                          v-model="form.expectedDeliveryTime"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择预期交货时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="修改人" prop="modifiedBy">
          <el-input v-model="form.modifiedBy" placeholder="请输入修改人" />
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="form.remarks" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <div style="display: grid; place-items: center;
                margin-top: 30px; margin-right: 10px;">
      <el-button
          type="primary"
          @click="handleGenerate"
      >采购订单生成</el-button>
    </div>

  </div>
</template>

<script setup name="OrderGenerate">
import {
  getPurchasePlan,
  delPurchasePlan,
  addPurchasePlan,
  updatePurchasePlan,
  listLatestPurchasePlan
} from "@/api/purchase/purchasePlan.js";
import { getSupplierList } from "@/api/purchase/rawProduct.js";
import useDictStore from '@/store/modules/dict'

const { proxy } = getCurrentInstance();

const orderGenerateList = ref([]);
const sortedList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const products = ref([]); //货品名称集合
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const { plan_purchase_status } = proxy.useDict("plan_purchase_status")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    rawProductName: null,
    demandDate: null,
    planStatus: null,
  },
  rules: {
    supplierCode: [
      { required: true, message: "供应商编码不能为空", trigger: "blur" }
    ],
    rawProductName: [
      { required: true, message: "货品名称不能为空", trigger: "blur" }
    ],
    quantity: [
      { required: true, message: "货品件数不能为空", trigger: "blur" }
    ],
    budget: [
      { required: true, message: "预算不能为空", trigger: "blur" }
    ],
    demandDate: [
      { required: true, message: "需求日期不能为空", trigger: "blur" }
    ],
    planStatus: [
      { required: true, message: "计划状态不能为空", trigger: "change" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

function parseCode(code) {
  const number = parseInt(code.slice(10), 10);
  return number;
}

function sortPurchasePlanList(oldList,newList) {
  newList.value = [...oldList.value].sort((a, b) => {
    return parseCode(a.planNo) - parseCode(b.planNo);
  });
}

/** 查询订单生成列表 */
function getList() {
  loading.value = true;
  listLatestPurchasePlan(queryParams.value).then(response => {
    orderGenerateList.value = response.rows;
    sortPurchasePlanList(orderGenerateList,sortedList)
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    planNo: null,
    supplierCode: null,
    rawProductBatch: null,
    rawProductName: null,
    quantity: null,
    budget: null,
    currencyType: null,
    currencyUnit: null,
    demandDate: null,
    expectedDeliveryTime: null,
    createdTime: null,
    modifiedDate: null,
    modifiedBy: null,
    planStatus: null,
    remarks: null
  };
  proxy.resetForm("ordergenerateRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.planNo);
  products.value = selection.map(item => item.rawProductName);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加订单生成";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _planNo = row.planNo || ids.value
  getPurchasePlan(_planNo).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改订单生成";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["ordergenerateRef"].validate(valid => {
    if (valid) {
      if (form.value.planNo != null) {
        updatePurchasePlan(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addPurchasePlan(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _planNos = row.planNo || ids.value;
  proxy.$modal.confirm('是否确认删除订单生成编号为"' + _planNos + '"的数据项？').then(function() {
    return delPurchasePlan(_planNos);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('purchasePlan/export', {
    ...queryParams.value
  }, `purchasePlan_${new Date().getTime()}.xlsx`)
}

/** 生成订单 **/
function handleGenerate(){
  getSupplierList(products.value).then(response => {
    proxy.$router.push({
      path:'/PurchaseOrder/OrderGenerate/PurchaseDetail',
      query:{
        planNoList:ids.value
      }
    });
  })
}

/** 转化订单购买状态 */
function getPlanPurchaseStatus(status) {
  if(status === '未开始'){
    return 'info';
  }
  else if(status === '超额完成'){
    return 'danger';
  }
  else{
    return 'success';
  }
}

getList();
</script>

<style scoped>
.custom-large-button {
  font-size: 17px; /* 调整字体大小 */
  padding: 15px 30px; /* 增加内边距 */
  height: 40px; /* 设置高度 */
  width: 120px; /* 设置宽度 */
}
</style>